﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Routing;

namespace MVC_basic.Helpers
{
    public class IPFilterAttribute : AuthorizeAttribute
    {
        public string AllowedIP { get; set; }

        protected override bool AuthorizeCore(HttpContextBase httpContext)
        {
            if (httpContext == null)
                throw new ArgumentNullException("httpContext");

            string userIpAddress = httpContext.Request.UserHostAddress;

            bool valid = checkIP(userIpAddress);

            return valid; 
        }

        private bool checkIP(string ipAdress)
        {
            List<string> ips = splitIps();
            foreach (string ip in ips)
            {
                if (ipAdress == ip)
                    return true;
            }
            return false;
        }

        private List<string> splitIps()
        {
            List<string> ips = new List<String>();
            var splitSingleIPs = AllowedIP.Split(',');
            foreach (string ip in splitSingleIPs)
                ips.Add(ip);
            return ips;
        }

        protected override void HandleUnauthorizedRequest(AuthorizationContext filterContext)
        {
            filterContext.Result = new RedirectToRouteResult(
                                   new RouteValueDictionary 
                                   {
                                       { "action", "Index" },
                                       { "controller", "Home" }
                                   });
        }
    }
}